package com.hytc.mymall.braodcastreciver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
import android.text.TextUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Joker on 2016/12/1.
 */

public class SmsBroadCastReceiver extends BroadcastReceiver
{
    private SMSReceiveListener listener;

    private String patternCode(final String s) {
        if (!TextUtils.isEmpty((CharSequence)s)) {
            final Matcher matcher = Pattern.compile("(?<!\\d)\\d{6}(?!\\d)").matcher(s);
            if (matcher.find()) {
                return matcher.group();
            }
        }
        return null;
    }

    public void onReceive(final Context context, final Intent intent) {
        final Object[] array = (Object[])intent.getExtras().get("pdus");
        for (int length = array.length, i = 0; i < length; ++i) {
            final SmsMessage fromPdu = SmsMessage.createFromPdu((byte[])array[i]);
            final String messageBody = fromPdu.getMessageBody();
            if (!TextUtils.isEmpty((CharSequence)fromPdu.getOriginatingAddress())) {
                final String patternCode = this.patternCode(messageBody);
                if (!TextUtils.isEmpty((CharSequence)patternCode)) {
                    this.listener.getVerifyCode(patternCode);
                }
            }
        }
    }

    public void setSMSReceiveListener(final SMSReceiveListener listener) {
        this.listener = listener;
    }

    public interface SMSReceiveListener
    {
        void getVerifyCode(final String p0);
    }
}
